﻿Imports System.Reflection
Namespace Messaging
    Friend NotInheritable Class MessageTopic
        'Credit for the original C# version goes to Team MediaPortal
        Private ReadOnly m_ID As String
        Private _messageType As Type
        Private ReadOnly handlers As New List(Of KeyValuePair(Of Object, MethodInfo))()
        Private Shared ReadOnly raisePointer As MethodInfo = GetType(MessageTopic).GetMethod("SendMessage", BindingFlags.Instance Or BindingFlags.NonPublic)
        Public Sub AddListener(ByVal Item As Object, ByVal info As MethodInfo)
            handlers.Add(New KeyValuePair(Of Object, MethodInfo)(Item, info))
        End Sub
        Public Property MessageType() As Type
            Get
                Return _messageType
            End Get
            Set(ByVal value As Type)
                _messageType = value
            End Set
        End Property
        Public Sub New(ByVal ID As String)
            m_ID = ID
        End Sub
        Public Sub AddMessagePublisher(ByVal Item As Object, ByVal Info As EventInfo)
            Dim Handler As [Delegate] = [Delegate].CreateDelegate(Info.EventHandlerType, Me, raisePointer)
            Info.AddEventHandler(Item, Handler)
        End Sub
        Friend Sub SendMessage(ByVal E As Message)
            [Global].Services.ServiceInstance.Get(Of Interfaces.ILogging).AddItem("Messaging: Sending " & m_ID & " Message", Logging.MessageType.General)
            For I As Integer = 0 To handlers.Count
                If I >= handlers.Count Then Exit For
                Dim Pair As KeyValuePair(Of Object, MethodInfo) = handlers(I)
                Pair.Value.Invoke(Pair.Key, New Object() {E})
            Next
        End Sub
    End Class
End Namespace